package com.example.springbootexcle.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.example.springbootexcle.config.FileConfig;
import com.example.springbootexcle.model.User;
import com.example.springbootexcle.service.UserService;
import com.example.springbootexcle.utils.ExcleUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author: xulinyi
 * @create: 2019-03-21 10:39
 **/
@Controller
public class UserController {
    @Resource
    private UserService userService;

    /**
     * 首页
     * @return
     */
    @GetMapping("/index")
    public String index() {
        return "index";
    }

    /**
     * excle下载
     * @param title
     * @param response
     */
    @GetMapping("/download")
    @ResponseBody
    public void downLoadExcel(String title,HttpServletResponse response) {
        String sheetName="用户";
       List<User> userList = userService.selectAll();
        ExcleUtils.downloadExcel(userList,title,sheetName,User.class,title+".xlsx",response);
    }

    /**
     * excle导入
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("fileName") MultipartFile file, HttpServletRequest request){
        if(file.isEmpty()){
            return "空文件";
        }
        //获取文件名
        String fileName = file.getOriginalFilename();
        //获取文件后缀
        String type =fileName.indexOf(".") != -1 ? fileName.split("[.]")[1] : null;
        //文件格式判断
        if (!Arrays.asList(FileConfig.UPLOAD_EXCLE_TYPES).contains(type.toLowerCase())) {
            return "文件类型不对";
        }

        ImportParams params = new ImportParams();
        //表格标题所占据的行数,默认0，代表没有标题
        params.setTitleRows(1);
        //表头所占据的行数行数,默认1，代表标题占据一行
        params.setHeadRows(1);
        List<User> list;
        try {
            //excel的数据
            list = ExcelImportUtil.importExcel(file.getInputStream(),User.class, params);
            //导入数据库
            userService.adds(list);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

}
